package org.osgroup.controller;

import org.osgroup.dto.*;
import org.osgroup.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单服务接口控制器
 */
@RestController
@RequestMapping("/api/food-order")
@CrossOrigin(origins = "*")
public class OrderController {
    
    @Autowired
    private OrderService orderService;
    
    /**
     * 提交订单
     */
    @PostMapping("/submit")
    public ResponseEntity<OrderSubmitResponse> submitOrder(@RequestBody OrderSubmitRequest request) {
        try {
            OrderSubmitResponse response = orderService.submitOrder(request);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            OrderSubmitResponse errorResponse = new OrderSubmitResponse();
            errorResponse.setCode(500);
            errorResponse.setMessage("订单提交失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    /**
     * 获取订单历史
     */
    @GetMapping("/history")
    public ResponseEntity<List<FoodOrder>> getOrderHistory(@RequestParam(required = false) String customerName) {
        try {
            List<FoodOrder> orders = orderService.getOrderHistory(customerName);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }
    
    /**
     * 获取订单详情
     */
    @GetMapping("/details/{orderNumber}")
    public ResponseEntity<FoodOrder> getOrderDetails(@PathVariable String orderNumber) {
        try {
            FoodOrder order = orderService.getOrderDetails(orderNumber);
            if (order != null) {
                return ResponseEntity.ok(order);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/cancel/{orderNumber}")
    public ResponseEntity<OrderCancelResponse> cancelOrder(@PathVariable String orderNumber) {
        try {
            OrderCancelResponse response = orderService.cancelOrder(orderNumber);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            OrderCancelResponse errorResponse = new OrderCancelResponse();
            errorResponse.setCode(500);
            errorResponse.setMessage("取消订单失败: " + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
}
